#! /bin/sh

case "@FW_NATIVE_PACKAGE_TYPE@" in
  deb)
    ;;
  rpm)
    ;;
  *)
    echo 'test-hooks: unknown package type @FW_NATIVE_PACKAGE_TYPE@' 1>&2
    exit 77
    ;;
esac

if test -d ../fw/bin  
  then
    PATH="`pwd`/../fw/bin:$PATH"
    export PATH
  fi

if test -z "$MAKE"
  then
    gmake=`which gmake`

    if test $? = 0 
      then
        MAKE=gmake
      else
        MAKE=make
      fi
  fi

(
set -x
rm -rf cvstmp
mkdir cvstmp
( 
  cd cvstmp &&
  cvs -d "`pwd`" init
)
test -h fw.local || ln -sf ../fw.local fw.local || exit 1
test -h share || ln -sf .. share || exit 1
CVSROOT="`pwd`/cvstmp"
export CVSROOT
testsdir="`pwd`"
rm -rf megatmp
{
  mkdir megatmp &&
  cd megatmp &&
  env FW_ROOT="$testsdir"                               \
  fw-init --name tmp                                    \
          --revision cvs                                \
          --template erlang 
} || exit 1
cd tmp
rm -f fw
mkdir fw
cwd=`pwd`
mkdir fw/bin
cp `env PATH="../../../fw/bin:$PATH" which fw-bootstrap` fw/bin
cp `env PATH="../../../fw/bin:$PATH" which fw-exec` fw/bin
cp `env PATH="../../../fw/bin:$PATH" which fw-init` fw/bin
cp `env PATH="../../../fw/bin:$PATH" which fw-package` fw/bin
(cd "../../../fw"; find . -print | cpio -pud "$cwd/fw")
(cd "../../../fw.local"; find template -print | cpio -pud "$cwd/fw")
(cd "../../../fw.local"; find m4 -print | cpio -pud "$cwd/fw")

# disable the addition of fw-template-erlang to the BUILD_DEPENDS since it 
# will not be installed at this point
perl -pi -e 's/^.*fw-template-erlang.*$//g' fw/template/erlang/load-config

./bootstrap && ./build --disable-erlrc && env FW_SKIP_TESTS=1 "${MAKE}" package 

case "@FW_NATIVE_PACKAGE_TYPE@" in
  deb)
    dpkg --control fw-pkgout/tmp_0.0.0-TEST1_all.deb

    for x in postinst postrm preinst prerm
      do
        diff -u ../../${x}.noerlrc DEBIAN/$x || exit 1
        "@CHECK_SHELL@" -n DEBIAN/$x || exit 1
      done
    dpkg --contents fw-pkgout/tmp_0.0.0-TEST1_all.deb | \
    grep erlrc >/dev/null && exit 1

    ;;
  rpm)
    rpm -q --scripts -p fw-pkgout/tmp-0.0.0-TEST1.noarch.rpm | \
    grep erlrc >/dev/null && exit 1

    rpm -ql -p fw-pkgout/tmp-0.0.0-TEST1.noarch.rpm | \
    grep erlrc >/dev/null && exit 1

    ;;
esac

./build && env FW_SKIP_TESTS=1 "${MAKE}" package 

case "@FW_NATIVE_PACKAGE_TYPE@" in
  deb)
    dpkg --control fw-pkgout/tmp_0.0.0-TEST1_all.deb
    for x in postinst postrm preinst prerm
      do
        diff -u ../../$x DEBIAN/$x || exit 1
        "@CHECK_SHELL@" -n DEBIAN/$x || exit 1
      done
    dpkg --contents fw-pkgout/tmp_0.0.0-TEST1_all.deb | \
    grep erlrc >/dev/null || exit 1

    ;;
  rpm)
    rpm -q --scripts -p fw-pkgout/tmp-0.0.0-TEST1.noarch.rpm | \
    grep erlrc >/dev/null || exit 1

    rpm -ql -p fw-pkgout/tmp-0.0.0-TEST1.noarch.rpm | \
    grep erlrc >/dev/null || exit 1

    ;;
esac

) > test-hooks.out 2>&1 || exit 1

exit 0
